package com.hc.serviceimpl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hc.entity.IncubSnapshotInfo;
import com.hc.entity.QcEquipment;
import com.hc.entity.QcEquipmentRecord;
import com.hc.exception.TlsRuntimeException;
import com.hc.mapper.QcEquipmentMapper;
import com.hc.mapper.QcEquipmentRecordMapper;
import com.hc.model.QcEquipmentFind;
import com.hc.model.QualityControlReport;
import com.hc.model.QualityControlReportList;
import com.hc.service.IncubSnapshotInfoService;
import com.hc.service.QcEquipmentRecordService;
import com.hc.service.QcEquipmentService;
import com.hc.util.DateUtil;
import com.hc.util.UserInfoPost;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LiuZhiHao
 * @date 2019/8/28 9:33
 * 描述:
 **/
@Service
public class QcEquipmentServiceImpl implements QcEquipmentService {

    @Autowired
    private QcEquipmentMapper qcEquipmentMapper;
    @Autowired
    private UserInfoPost userInfoPost;
    @Autowired
    private QcEquipmentRecordMapper qcEquipmentRecordMapper;
    @Autowired
    private QcEquipmentRecordService qcEquipmentRecordService;

    @Autowired
    private IncubSnapshotInfoService infoService;


    @Override
    public void saveEquipment(QcEquipment qcEquipment) {
        Integer id = qcEquipment.getId();
        String deviceName = qcEquipment.getDeviceName();
        if (null == id) {
            //新增设备设备名称不能重复
            QcEquipment qcEquipment1 = qcEquipmentMapper.selectOne(Wrappers.lambdaQuery(new QcEquipment()).eq(QcEquipment::getDeviceName, deviceName).eq(QcEquipment::getEnable, "0"));
            if (null != qcEquipment1) {
                throw new TlsRuntimeException("设备名称重复");
            }
            //气瓶室内只存在一个
            String classifyId = qcEquipment.getClassifyId();
            if (StringUtils.equals(classifyId, "3")) {
                QcEquipment qcEquipment2 = qcEquipmentMapper.selectOne(Wrappers.lambdaQuery(new QcEquipment()).eq(QcEquipment::getClassifyId, classifyId).eq(QcEquipment::getEnable, "0"));
                if (null != qcEquipment2) {
                    throw new TlsRuntimeException("气瓶室类型只能存在一个");
                }
            }
            //液氮罐只能存在三个
            if (StringUtils.equals(classifyId, "2")) {
                Integer integer = qcEquipmentMapper.selectCount(Wrappers.lambdaQuery(new QcEquipment()).eq(QcEquipment::getClassifyId, classifyId).eq(QcEquipment::getEnable, "0"));
                if (null != integer) {
                    if (integer >= 3) {
                        throw new TlsRuntimeException("液氮罐类型只能存在三个");
                    }
                }
            }
            qcEquipment.setCreateBy(qcEquipment.getCreateBy());
            qcEquipment.setCreateTime(new Date());
            qcEquipmentMapper.insert(qcEquipment);
            qcEquipment.setScanidentify("ZK" + qcEquipment.getId() + System.currentTimeMillis());
            qcEquipmentMapper.updateById(qcEquipment);
        } else {
            if (StringUtils.isNotEmpty(deviceName)) {
                //修改设备设备名称不能重复
                QcEquipment qcEquipment1 = qcEquipmentMapper.selectOne(Wrappers.lambdaQuery(new QcEquipment()).eq(QcEquipment::getId, id));
                if (!StringUtils.equals(qcEquipment1.getDeviceName(), deviceName)) {
                    QcEquipment qcEquipment2 = qcEquipmentMapper.selectOne(Wrappers.lambdaQuery(new QcEquipment()).eq(QcEquipment::getDeviceName, deviceName));
                    if (null != qcEquipment2) {
                        throw new TlsRuntimeException("设备名称不能重复");
                    }
                }
            }
            qcEquipment.setUpdateTime(new Date());
            qcEquipment.setUpdateBy(qcEquipment.getCreateBy());
            qcEquipmentMapper.updateById(qcEquipment);
        }
    }

    @Override
    public Page<QcEquipment> getallqcequitmentByCid(QcEquipmentFind qcEquipmentFind) {
        Page<QcEquipment> page = new Page<>();
        page.setCurrent(qcEquipmentFind.getCurrentPage());
        page.setSize(qcEquipmentFind.getPageSize());
        List<QcEquipment> qcEquipmentPage = qcEquipmentMapper.getQcEquipmentPage(page, qcEquipmentFind);
        Set<String> collect = qcEquipmentPage.stream().map(QcEquipment::getCreateBy).collect(Collectors.toSet());
        Map<String, String> allSysUserinfoByIds = userInfoPost.getAllSysUserinfoByIds(collect);
        qcEquipmentPage.forEach(s -> {
            String createBy = s.getCreateBy();
            String createName = allSysUserinfoByIds.get(createBy);
            s.setUserName(createName);
            s.setMt100Sn(s.getMt100Sn()==null?"":s.getMt100Sn());
            s.setMt300Sn(s.getMt300Sn()==null?"":s.getMt300Sn());
            s.setMt700Sn(s.getMt700Sn()==null?"":s.getMt700Sn());
        });

        page.setRecords(qcEquipmentPage);
        return page;
    }


    @Override
    public void deleteEquipment(int id) {
        qcEquipmentMapper.deleteById(id);
    }

    @Override
    public QcEquipment getQcEquipmentByScId(String scId) {
        LambdaQueryWrapper<QcEquipment> eq = Wrappers.lambdaQuery(new QcEquipment())
                .eq(QcEquipment::getScanidentify, scId)
                .eq(QcEquipment::getEnable, "0");
        return qcEquipmentMapper.selectOne(eq);
    }

    /**
     * 根据设备类型id获取所有该设备的名称
     * @param classifyId
     * @return
     */
    @Override
    public List<QcEquipment> getAllDeviceNameForClassifyId(String classifyId) {
        return qcEquipmentMapper.getAllDeviceNameForClassifyId(classifyId);
    }

    @Override
    public Map<String, String> feacheqtype(String day) {
        Map<String,String> map = new HashMap<>();
        List<QcEquipmentRecord> feacheqtype = qcEquipmentRecordMapper.feacheqtype(day);
        if (CollectionUtils.isEmpty(feacheqtype)){
            throw  new TlsRuntimeException("暂无信息");
        }
        Map<String, List<QcEquipmentRecord>> collect = feacheqtype.stream().collect(Collectors.groupingBy(QcEquipmentRecord::getWorkStatus));
        collect.forEach((k,v)->{
            Set<String> collect1 = v.stream().map(QcEquipmentRecord::getCreateBy).collect(Collectors.toSet());
            Map<String, String> allSysUserinfoByIds = userInfoPost.getAllSysUserinfoByIds(collect1);
            Set<String> strings = allSysUserinfoByIds.keySet();
            StringBuffer stringBuffer = new StringBuffer();
            strings.forEach(s-> stringBuffer.append(",").append(allSysUserinfoByIds.get(s)));
            map.put(k,stringBuffer.toString());

        });
        return  map;
    }

    @Override
    public Map<String, Map<String, String>> feacheqtypeClass(String day, String classId) {
        Map<String, Map<String,String>> mapMap =new TreeMap<>();
        List<QcEquipmentRecord> feacheqtype = qcEquipmentRecordMapper.feacheqtypeClass(day,classId);
        if (CollectionUtils.isEmpty(feacheqtype)){
            throw  new TlsRuntimeException("暂无信息");
        }
        Map<String, List<QcEquipmentRecord>> collect2 = feacheqtype.stream().collect(Collectors.groupingBy(p -> DateUtil.paseDate(p.getCreateTime())));
        collect2.forEach((k,v)->{
            Map<String, List<QcEquipmentRecord>> collect = v.stream().collect(Collectors.groupingBy(QcEquipmentRecord::getWorkStatus));
            Map<String,String> map = new HashMap<>();
            collect.forEach((m,l)->{
                Set<String> collect1 =l.stream().map(QcEquipmentRecord::getCreateBy).collect(Collectors.toSet());
                Map<String, String> allSysUserinfoByIds = userInfoPost.getAllSysUserinfoByIds(collect1);
                Set<String> strings = allSysUserinfoByIds.keySet();
                StringBuffer stringBuffer = new StringBuffer();
                strings.forEach(s-> stringBuffer.append(",").append(allSysUserinfoByIds.get(s)));
                map.put(m.equals("1") ?"上班":"下班",stringBuffer.toString());
            });
            mapMap.put(k,map);
        });
        return mapMap;
    }

    @Override
    public void snapshotTest(String date) {
        String beforeZero;
        if (StringUtils.isEmpty(date)) {
            beforeZero = DateUtil.getBeforeZero();
        } else {
            beforeZero = date;
        }
        List<QualityControlReportList> qualityControlReportLists= qcEquipmentRecordService.getQualityControlReportEveryDayForPYXNew(beforeZero, "1");
        List<IncubSnapshotInfo>  incubSnapshotInfos  =  new ArrayList<>();
        if (CollectionUtils.isNotEmpty(qualityControlReportLists)){
            for (QualityControlReportList qualityControlReportList : qualityControlReportLists) {
                IncubSnapshotInfo incubSnapshotInfo  = new IncubSnapshotInfo();
                incubSnapshotInfo.setEqId(String.valueOf(qualityControlReportList.getEqId()));
                incubSnapshotInfo.setDeviceName(qualityControlReportList.getDeviceName());
                incubSnapshotInfo.setDate(qualityControlReportList.getDate());
                List<QualityControlReport> qcrs = qualityControlReportList.getQcrs();
                if (CollectionUtils.isNotEmpty(qcrs)){
                    incubSnapshotInfo.setQcrs(JSONUtil.toJsonStr(qcrs));
                }
                incubSnapshotInfo.setMaintenanceRecord(qualityControlReportList.getMaintenanceRecord());
                List<Long> qcMonitorIds = qualityControlReportList.getQcMonitorIds();
                if (CollectionUtils.isNotEmpty(qcMonitorIds)){
                    incubSnapshotInfo.setQcMonitorIds(JSONUtil.toJsonStr(qcMonitorIds));
                }
                incubSnapshotInfo.setSignatureId(qualityControlReportList.getSignatureId());
                incubSnapshotInfo.setIsSignature(qualityControlReportList.getIsSignature());
                incubSnapshotInfo.setSelfCheck(qualityControlReportList.getSelfCheck());
                incubSnapshotInfo.setChecker(qualityControlReportList.getChecker());
                incubSnapshotInfo.setIsAddLiquidNitrogen(qualityControlReportList.getIsAddLiquidNitrogen());
                incubSnapshotInfo.setCreateTime(LocalDateTime.now());
                incubSnapshotInfos.add(incubSnapshotInfo);
            }
            infoService.saveBatch(incubSnapshotInfos);
        }
    }

    @Override
    public List<QcEquipment> listEq() {
        LambdaQueryWrapper<QcEquipment> eq = Wrappers.lambdaQuery(new QcEquipment())
                .eq(QcEquipment::getEnable, "0");
        return qcEquipmentMapper.selectList(eq);
    }
}
